package com.testsoap;

import java.util.Calendar;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class TestSOAP extends Activity {
	
	private static final String namespace = "http://cliffhanger.es/";
	private static final String url = "http://www.cliffhanger.es/API/webservice.php";
	private TextView mDateDisplay;
    private Button mPickDate;
    private int mYear;
    private int mMonth;
    private int mDay;
    Episode[] Episodios;
    static final int DATE_DIALOG_ID = 0;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.main);
    	
    	// capture our View elements
        mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
        mPickDate = (Button) findViewById(R.id.pickDate);

        // add a click listener to the button
        mPickDate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
            }
        });

        // get the current date
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
    	
    	updateDisplay();
    	}
    
 // updates the date in the TextView
    private void updateDisplay() {
        mDateDisplay.setText(
            new StringBuilder()
                    // Month is 0 based so add 1
                    .append(mMonth + 1).append("-")
                    .append(mDay).append("-")
                    .append(mYear).append(" "));
        
            	
    	SoapObject request = new SoapObject(namespace, "EpisodeByDate");
    	request.addProperty ( "day", mDay);
    	request.addProperty ( "month", mMonth+1);
    	request.addProperty ( "year", mYear);
    	       
    	SoapObject result=null;

    	SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11 );
    	envelope.addMapping(namespace, "Episode",new Episode().getClass());
    	  	
    	result = APICall(request, envelope, "EpisodeByDate", "EpisodeByDate", namespace, url);
    	
    	if(result != null){
	        Episodios = new Episode[result.getPropertyCount()];
	    	for(int i=0;i<result.getPropertyCount();i++) {
	    		SoapObject pojoSoap = (SoapObject) result.getProperty(i);
	    		Episodios[i] = new Episode((Integer) pojoSoap.getProperty("id"), 
	    				(Integer) pojoSoap.getProperty("temporada"), 
	    				(Integer) pojoSoap.getProperty("capitulo"),
	    				pojoSoap.getProperty("fecha_emision").toString(), 
	    				pojoSoap.getProperty("overview").toString(), 
	    				pojoSoap.getProperty("nombre").toString(),
	    				pojoSoap.getProperty("serie").toString());
	    	}
    	}
    	EpisodeAdapter adaptador = new EpisodeAdapter(this,Episodios); 	 
    	ListView lstOpciones = (ListView)findViewById(R.id.LstOpciones);  	 
    	lstOpciones.setAdapter(adaptador);
    	lstOpciones.setTextFilterEnabled(true);

    	lstOpciones.setOnItemClickListener(new OnItemClickListener() {
    		
    	    public void onItemClick(AdapterView<?> parent, View view,
    	        int position, long id) {
    	      // When clicked, show a toast with the TextView text
    	    	/*AlertDialog.Builder dialog = new AlertDialog.Builder(getApplicationContext());
    			  dialog.setTitle("Sinopsis");
    			  dialog.setMessage("test");
    			  dialog.show();*/
    	    	
    	      Toast.makeText(getApplicationContext(), "Sinopsis: " + Episodios[position].overview.toString(),
    	          Toast.LENGTH_LONG).show();
    	    }
    	  });

	
    }
    
    public SoapObject APICall(SoapObject request,SoapSerializationEnvelope envelope,String method, String SoapAction, String namespace, String url){   	       
    	SoapObject result=null;

    	HttpTransportSE httpt = new HttpTransportSE(url);
    	envelope.dotNet = false;
    	envelope.bodyOut = request;
    	try
    	{
    	     httpt.debug = true;
    	     httpt.call("EpisodeByDate", envelope);
    	     result = (SoapObject)envelope.getResponse();
    	}
    	catch(Exception e)
    	{
    	     e.printStackTrace();
    	     return null;
    	}
    	return result;
    }
    
    private DatePickerDialog.OnDateSetListener mDateSetListener =
        new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year, 
                                  int monthOfYear, int dayOfMonth) {
                mYear = year;
                mMonth = monthOfYear;
                mDay = dayOfMonth;
                updateDisplay();
            }
        };
        
        @Override
        protected Dialog onCreateDialog(int id) {
            switch (id) {
            case DATE_DIALOG_ID:
                return new DatePickerDialog(this,
                            mDateSetListener,
                            mYear, mMonth, mDay);
            }
            return null;
        }
        
        
}